package ar.edu.utn.frgp.mvc.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.utn.frgp.banco.exceptions.DataAccessException;

import ar.edu.utn.frgp.beans.MessageBean;
import ar.edu.utn.frgp.banco.domain.Cliente;
import ar.edu.utn.frgp.banco.dao.Implements.ImpClientes;
/**
 * Servlet implementation class login
 */
public class LogInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LogInServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException{
		// TODO Auto-generated method stub
		Cliente cliente = null;
		String DNI = req.getParameter("DNI");
		String pass = req.getParameter("pass");

		// por defecto trae 1
		try {
			cliente = validarUsuario(DNI, pass);
		} catch (DataAccessException e) {
			
		}

		// req.getSession().invalidate();

		if (DNI != "" && pass != "") {
			if (cliente != null) {
				req.getSession().setAttribute("ban_cuentas", "");
				req.getSession().setAttribute("ID_Cliente",cliente.getID_Cliente());
				req.getSession().setAttribute("nombre",cliente.getNombre());
				req.getSession().setAttribute("apellido",cliente.getApellido());
				req.getRequestDispatcher("SeleccionCuentas.jsp").forward(req, resp);
//				req.getRequestDispatcher("MainCliente.jsp").forward(req, resp);

			}else{

				// no ingreso usr o clave
				MessageBean aux = new MessageBean();
				aux.setMensaje("Usuario o Clave incorrecta");
				req.setAttribute("msj", aux);
				req.getRequestDispatcher("index.jsp").forward(req, resp);
			}
		}else{

		// no ingreso usr o clave
		MessageBean aux = new MessageBean();
		aux.setMensaje("Usuario o Clave incorrecta");
		req.setAttribute("msj", aux);
		req.getRequestDispatcher("index.jsp").forward(req, resp);
		}

	}

	private Cliente validarUsuario(String DNI, String password) throws DataAccessException {
		Cliente c = null; 
		ImpClientes clientedao = new ImpClientes();
		c = clientedao.ObtenerCliente(DNI);
		if (c != null){
			if(c.getClave().equals(password)){
				return c;
			}
		}
		return null;
	}
}
